package com.lqq.chapter10.pool;

import java.util.concurrent.*;

/**
 * @Author lqq677
 * @Date 2021/8/12 21:00
 * @Description ThreadPoolExecutor自定义线程池，场景：火车站 3 个售票口，10个用户买票
 */

//自定义线程池类
class MyThreadPool {
    /**
     * int corePoolSize,线程池的核心线程数
     * int maximumPoolSize,能容纳的最大线程数
     * long keepAliveTime,空闲线程存活时间
     * TimeUnit unit,存活的时间单位
     * BlockingQueue<Runnable> workQueue,存放提交但未执行任务的队列
     * ThreadFactory threadFactory,创建线程的工厂类
     * RejectedExecutionHandler handler 等待队列满后的拒绝策略
     **/
    public static ThreadPoolExecutor threadPool() {
        return new ThreadPoolExecutor(
                3,
                3,
                60L,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()
        );
    }
}

public class ThreadPoolExecutorDemo {

    //办理业务
    public static void execute(int n, ExecutorService threadPool) {

        try {
            for (int i = 1; i <= n; i++) {//模拟10个顾客请求
                //执行
                threadPool.execute(() -> {
                    try {
                        System.out.println(Thread.currentThread().getName() + " 窗口,开始卖票...");
                        //模拟暂停
                        TimeUnit.SECONDS.sleep(2);
                        System.out.println(Thread.currentThread().getName() + " 窗口卖票结束");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
             });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭
            threadPool.shutdown();
        }
    }

    public static void main(String[] args) {
        //创建线程池
        ThreadPoolExecutor threadPool = MyThreadPool.threadPool();
        //模拟10个用户买票
        execute(10, threadPool);
    }

}
